package com.example.mypetstoreback.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mypetstoreback.common.CommonResponse;
import com.example.mypetstoreback.mapper.itemMapper;
import com.example.mypetstoreback.mapper.productMapper;
import com.example.mypetstoreback.pojo.Item;
import com.example.mypetstoreback.pojo.Product;
import com.example.mypetstoreback.service.productService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class productServiceImpl implements productService {
    @Autowired
    private productMapper productMapper;
    @Autowired
    private itemMapper itemMapper;

    @Override
    public CommonResponse<List<Product>> getProductByCategoryId(String categoryid) {
        QueryWrapper<Product> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("category",categoryid);
        List<Product> products =productMapper.selectList(queryWrapper);
        return CommonResponse.createForSuccess(products);
    }

    @Override
    public CommonResponse<Product> addProduct(Product product) {
        int result = productMapper.insert(product);
        if (result==1){
            return CommonResponse.createForSuccess(product);
        }else {
            return CommonResponse.createForError("服务器异常");
        }
    }

    @Override
    public CommonResponse<String> updateProductByProductId(Product product) {
        int result = productMapper.updateById(product);
        if (result==1){
            return CommonResponse.createForSuccess("修改成功！");
        }else {
            return CommonResponse.createForError("修改失败！");
        }
    }


    @Override
    public CommonResponse<String> deleteProductByProductId(String productId) {
        //实现数据库表之间的约束，将product删除对应的item也要删除；
        QueryWrapper<Item> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("productid",productId);
        int result1 = itemMapper.delete(queryWrapper);
        int result = productMapper.deleteById(productId);
        if (result==1&&result1==1){
            return CommonResponse.createForSuccess("删除成功！");
        }else {
            return CommonResponse.createForError("删除失败！");
        }
    }

}
